﻿using NetTaste;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Text.RegularExpressions;
using QiAdmin.Core;
using QiAdmin.Core.Utils.Encryption;

namespace QiAdmin.WebApi.MiddleWares
{
    public class CheckSign
    {
        readonly RequestDelegate _next;
        public CheckSign(RequestDelegate next)
        {
            _next = next;
        }
        public async Task InvokeAsync(HttpContext context)
        {
            if (!App.AppSettings.System.IgnoreVerifySignPaths.ToList().Exists(s => context.Request.Path.ToString().Contains(s)))
            {
                if (!await CheckRequestSign(context))
                {
                    return;
                }
            }
            await _next(context);

        }
        async Task<bool> CheckRequestSign(HttpContext context)
        {
            string signKey = "-zero";
            bool isCheck = true;
            string errorMsg = JsonConvert.SerializeObject(new ApiJsonResult(ResultType.Error, "参数错误"));
            if (context.Request.Method.ToLower() == "post")
            {
                if (!context.Request.Headers.ContainsKey("sign"))
                {
                    isCheck = false;
                    await context.Response.WriteAsync(errorMsg);
                }
                else
                {
                    string inputSign = context.Request.Headers["sign"].ToString();
                    string parse = RsaUtil.DecryptPkcs8(inputSign, App.AppSettings.System.SignPrivateKey);
                    string token = context.Request.Headers[App.AppSettings.System.TokenTag].ToString() + signKey;
                    if (token.Length > 50)
                    {
                        token = token.Substring(0, 50);
                    }
                    if (parse != token)
                    {
                        isCheck = false;
                        context.Response.ContentType = "text/html;charset=utf-8";
                        await context.Response.WriteAsync(errorMsg);
                    }
                }
            }
            return isCheck;
        }
    }
}
